<template>
  <a-drawer
    v-model:open="vdata.isShow"
    :title="vdata.isAdd ? '新增{{ table.common.label }}' : '编辑{{ table.common.label }}'"
    width="50%"
    :mask-closable="false"
    @close="vdata.isShow = false"
  >
    <a-form
      ref="itemForm"
      :model="vdata.itemData"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 15 }"
      :rules="rules"
    >
      <a-row justify="space-between" type="flex">
        {%- for field_name, field in columns.items() %}
        {%- if field.naming.field_name not in ['createdAt', 'updatedAt'] %}
        <a-col :span="12">
          <a-form-item label="{{ field.common.label }}" name="{{ field.naming.field_name }}">
            {%- if field.mark.enum_options %}
            <a-select v-model:value="vdata.itemData.{{ field.naming.field_name }}">
              {%- for option in field.mark.enum_options %}
              <a-select-option value="{{ option.value }}">{{ option.label }}</a-select-option>
              {%- endfor %}
            </a-select>
            {%- elif field.derived.ts.type == 'string' and field.naming.field_name in ['birthDate', 'enrollDate'] %}
            <a-date-picker
              v-model:value="vdata.itemData.{{ field.naming.field_name }}"
              format="YYYY-MM-DD"
              placeholder="请输入{{ field.common.label }}"
            />
            {%- else %}
            {%- set component_type = field.derived.ui.vue_antd_component %}
            <{{ component_type }} v-model:value="vdata.itemData.{{ field.naming.field_name }}" placeholder="请输入{{ field.common.label }}" />
            {%- endif %}
          </a-form-item>
        </a-col>
        {%- endif %}
        {%- endfor %}
      </a-row>
    </a-form>

    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="vdata.isShow = false">
        <CloseOutlined /> 取消
      </a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOk">
        <CheckOutlined /> 保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { {{ table.derived.naming.class_name }} } from "./types";
import dayjs from 'dayjs';
import { api{{ table.derived.naming.class_name }}Add, api{{ table.derived.naming.class_name }}Edit } from './api';

interface State {
  isAdd: boolean;
  isShow: boolean;
  confirmLoading: boolean;
  itemData: Partial<{{ table.derived.naming.class_name }}>;
  record: Partial<{{ table.derived.naming.class_name }}> | null;
}

const props = defineProps({
  callbackFunc: { type: Function, default: () => {} }
});

const vdata = reactive<State>({
  isAdd: true,
  isShow: false,
  confirmLoading: false,
  itemData: {},
  record: null
});

const itemForm = ref();

// 表单验证规则
const rules = {
{%- for field_name, field in columns.items() %}
{%- if field.naming.field_name not in ['createdAt', 'updatedAt', 'remark'] %}
  {{ field.naming.field_name }}: [{ required: true, message: "请输入{{ field.common.description }}", trigger: "blur" }],
{%- endif %}
{%- endfor %}
};

function show(record: Partial<{{ table.derived.naming.class_name }}> | null) {
  if (itemForm.value) {
    itemForm.value.resetFields();
  }

  vdata.isAdd = !record;
  vdata.itemData = {};
  vdata.confirmLoading = false;

  if (!vdata.isAdd && record) {
    vdata.record = record;
    vdata.itemData = {
      ...record,
      // 只转换业务相关的日期字段
      birthDate: record.birthDate ? dayjs(record.birthDate) : undefined,
      enrollDate: record.enrollDate ? dayjs(record.enrollDate) : undefined
    };
  }

  vdata.isShow = true;
}

function handleOk() {
  itemForm.value.validate().then(() => {
    vdata.confirmLoading = true;

    // 只处理业务相关的日期字段
    const submitData: Partial<{{ table.derived.naming.class_name }}> = {
      ...vdata.itemData,
      birthDate: dayjs.isDayjs(vdata.itemData.birthDate)
        ? vdata.itemData.birthDate.format('YYYY-MM-DD')
        : vdata.itemData.birthDate,
      enrollDate: dayjs.isDayjs(vdata.itemData.enrollDate)
        ? vdata.itemData.enrollDate.format('YYYY-MM-DD')
        : vdata.itemData.enrollDate
    };

    const apiCall = vdata.isAdd
      ? api{{ table.derived.naming.class_name }}Add(submitData)
      : api{{ table.derived.naming.class_name }}Edit(vdata.record?.id as number, submitData);

    apiCall
      .then(() => {
        vdata.isShow = false;
        vdata.confirmLoading = false;
        props.callbackFunc();
      })
      .catch(() => {
        vdata.confirmLoading = false;
      });
  });
}

defineExpose({ show });
</script>

<style scoped>
.drawer-btn-center {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>